#ifndef SQLCONNPOOL_H
#define SQLCONNPOOL_H

#include<mysql/mysql.h>
#include<string>
#include<queue>
#include<mutex>
#include<semaphore.h>
#include<thread>
#include"../Log/log.h"

// 创建好一些连接以供备用，防止使用时创建释放消耗资源
class SqlConnPool {
public:
    static SqlConnPool* Instance();

    MYSQL* GetConn();
    void FreeConn(MYSQL* conn);
    int GetFreeConnCount();

    void Init(const char* host, int port, const char* user,
                const char* pwd, const char* dbName, int connSize);
    void ClosePool();

private:
    SqlConnPool(); //私有构造
    ~SqlConnPool(); //私有析构

    int MAX_CONN_;  // 最大的连接数
    int useCount_;  // 当前的用户数
    int freeCount_; // 空闲的用户数

    std::queue<MYSQL*> connQue_;    // 队列MYSQL指针对象
    std::mutex mtx_;    // 互斥锁
    sem_t semId_;       // 信号量
};

// RAII实现
class SqlConnRAII {
public:
    SqlConnRAII(MYSQL** sql, SqlConnPool *connpool) {
        assert(connpool);
        *sql = connpool->GetConn();
        sql_ = *sql;
        connpool_ = connpool;
    }
    
    ~SqlConnRAII() {
        if(sql_) { connpool_->FreeConn(sql_); }
    }
    
private:
    MYSQL *sql_;
    SqlConnPool* connpool_;
};


#endif